package com.xy.controller.admin;

import com.xy.base.BaseApiController;
import com.xy.base.RestResponse;
import com.xy.domain.Department;
import com.xy.domain.Major;
import com.xy.domain.User;
import com.xy.domain.UserEventLog;
import com.xy.domain.enums.UserStatusEnum;
import com.xy.repository.DepartmentMapper;
import com.xy.repository.MajorMapper;
import com.xy.service.AuthenticationService;
import com.xy.service.UserEventLogService;
import com.xy.service.UserService;
import com.xy.viewmodel.admin.user.*;
import com.github.pagehelper.PageInfo;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;


@RestController("AdminUserController")
@RequestMapping(value = "/api/admin/user")
@PreAuthorize("hasAnyRole('ADMIN', 'TEACHER')")
public class UserController extends BaseApiController {

    private final UserService userService;
    private final UserEventLogService userEventLogService;
    private final AuthenticationService authenticationService;

    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private MajorMapper majorMapper;

    @Autowired
    public UserController(UserService userService, UserEventLogService userEventLogService, AuthenticationService authenticationService) {
        this.userService = userService;
        this.userEventLogService = userEventLogService;
        this.authenticationService = authenticationService;
    }


//    @PreAuthorize("hasRole('STUDENT')")
    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<User>> pageList(@RequestBody UserPageRequestVM model) {
        PageInfo<User> pageInfo = userService.userPage(model);
        return RestResponse.ok(pageInfo);
    }


    @RequestMapping(value = "/event/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserEventLog>> eventPageList(@RequestBody UserEventPageRequestVM model) {
        PageInfo<UserEventLog> pageInfo = userEventLogService.page(model);
        return RestResponse.ok(pageInfo);
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> select(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        UserResponseVM userVO = UserResponseVM.from(user);
        List<Department> departments = departmentMapper.listDepartements();
        List<Major> majors = majorMapper.listByDepId(userVO.getDepartNum());
        userVO.setDepartments(departments);
        userVO.setMajors(majors);

        return RestResponse.ok(userVO);
    }

    @RequestMapping(value = "/current", method = RequestMethod.POST)
    public RestResponse<User> current() {
        User user = getCurrentUser();
        return RestResponse.ok(user);
    }

    /**
     * 该方法包含新增/修改功能
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse<User> edit(@RequestBody @Valid User model) {

        if (model.getId() == null) {  //create
            User existUser = userService.getUserByUserName(model.getRealName());
            if (null != existUser) {
                return new RestResponse<>(2, "用户已存在");
            }

            if (StringUtils.isBlank(model.getPassword())) {
                return new RestResponse<>(3, "密码不能为空");
            }
            String encodePwd = authenticationService.pwdEncode(model.getPassword());
            model.setPassword(encodePwd);
            model.setLastActiveTime(new Date());
            model.setDeleted(false);
            model.setUpdateTime(new Date());
            int state = userService.insert(model);
            if (state == 1) {
                return new RestResponse<>(1, "增加用户成功");
            }
            return new RestResponse<>(501, "增加失败");
        }

        // update...
        if (!StringUtils.isEmpty(model.getPassword())) {
            String encodePwd = authenticationService.pwdEncode(model.getPassword());
            model.setPassword(encodePwd);
        }
        // model.setNickname(RandomUtil.randomString("study", 7));
        model.setLastActiveTime(new Date());
        model.setDeleted(false);
        model.setUpdateTime(new Date());
        userService.updateByIdFilter(model);

        return RestResponse.ok(model);
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public RestResponse<Void> update(@RequestBody @Valid UserUpdateVM model) {
        User user = userService.selectById(getCurrentUser().getId());
        modelMapper.map(model, user);
        user.setUpdateTime(new Date());
        userService.updateByIdFilter(user);
        return RestResponse.ok();
    }


    @RequestMapping(value = "/changeStatus/{id}", method = RequestMethod.POST)
    public RestResponse<Integer> changeStatus(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        UserStatusEnum userStatusEnum = UserStatusEnum.fromCode(user.getStatus());
        Integer newStatus = userStatusEnum == UserStatusEnum.Enable ? UserStatusEnum.Disable.getCode() : UserStatusEnum.Enable.getCode();
        user.setStatus(newStatus);
        user.setUpdateTime(new Date());
        userService.updateByIdFilter(user);
        return RestResponse.ok(newStatus);
    }


    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse<Void> delete(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        user.setDeleted(true);
        userService.updateByIdFilter(user);
        return RestResponse.ok();
    }


    // @RequestMapping(value = "/selectByUserName", method = RequestMethod.POST)
    // public RestResponse<List<KeyValue>> selectByUserName(@RequestBody String userName) {
    //     List<KeyValue> keyValues = userService.selectByUserName(userName);
    //     return RestResponse.ok(keyValues);
    // }

}
